<?php

class Backdoor_Model_AdviserMapper
{
    protected $_dbTable;

    public function getDbTable() {
        if (null === $this->_dbTable) {
            $this->setDbTable('Application_Model_DbTable_Adviser');
        }
        return $this->_dbTable;
    }

    public function setDbTable($dbTable) {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Ungueltige Gateway-Klasse fuer Tabellendaten');
        }
        $this->_dbTable = $dbTable;
    }

    public function save(Application_Model_Adviser $adviser) {
        $data = array(
            'id' => $$adviser->getId(),
            'username' => $adviser->getUsername(),
            'password' => $adviser->getPassword(),
            'email' => $adviser->getEmail());
        if (null === $adviser->getId()) {
            unset($data['id']);
            $data['registered'] = time();
            $data['active'] = 0;
            
            $adviser->setId($this->getDbTable()->insert($data));
        } else {
            $data['modified'] = time();
            $this->getDbTable()->update($data, array('id = ?' => $data['id']));
        }
        return $this;
    }

    public function find($id, Application_Model_Adviser $adviser) {
        $result = $this->getDbTable()->find($id);
        if (0 == count($result)) {
            return null;
        }
        $row = $result->current();
        $adviser->setId($row['id'])
                ->setUsername($row['userkname'])
                ->setPassword($row['password'])
                ->setEmail($row['email']);
    }

    public function delete($adviserID) {
        if ($adviserID instanceof Application_Model_Adviser) {
            $adviserID = $adviserID->id;
        }
        return $this->getDbTable()->delete(array('id = ?' => $adviserID));
    }

}